from fastapi import FastAPI
import os
app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}


@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}

mus_path = '\home'

@app.get("/getFileList")
async def get_File_list():
    directory_structure = get_directory_structure(mus_path)
    return directory_structure


# 获取指定路径下的子文件夹及其文件（去掉文件后缀名）
def get_directory_structure(path: str):
    if not os.path.exists(path):
        return {"error": "Path does not exist"}

    result = {"path": path, "folders": []}

    # 遍历路径下的所有子文件夹
    for folder_name in os.listdir(path):
        folder_path = os.path.join(path, folder_name)
        if os.path.isdir(folder_path):  # 确保是文件夹
            files = []
            # 遍历子文件夹下的所有文件
            for file_name in os.listdir(folder_path):
                file_path = os.path.join(folder_path, file_name)
                if os.path.isfile(file_path):  # 确保是文件
                    # 去掉文件后缀名
                    file_name_without_ext = os.path.splitext(file_name)[0]
                    files.append(file_name_without_ext)
            # 将文件夹及其文件添加到结果中
            result["folders"].append({"folder_name": folder_name, "files": files})

    return result